<?php

namespace app\index\controller;

use app\model\MemberAutonym;
use app\model\MemberBuy;
use app\model\MemberTransfer;
use app\model\Operatingcity;
use app\model\Order;
use think\exception\ValidateException;
use app\model\Member;
use app\model\Users;
use app\model\Agent;
use app\model\Curl;
use app\model\WxBizDataCrypt;
use app\model\Config;
use app\model\CouponReceive;
use app\model\Technical;
use app\model\Wxmini;
use app\model\Openid;
use app\model\OrderStaff;


use EasyWeChat\Factory;

class MemberController extends Base
{
	public function detail()
	{
		$this->updatanickname();
		$Membermob = new Member;
		$memberinfo = $Membermob->getUserByWechat();

		$memberinfo['is_agent'] = (int) $memberinfo['is_agent'];

		$user_id = $memberinfo['id'];
		if ($memberinfo['primaryuid']) {
			$user_id = $memberinfo['primaryuid'];
		}

		$user = Users::getuserbyuid($user_id);

		if (!empty($user)) {
			$memberinfo['is_user'] = 1;
		} else {
			$memberinfo['is_user'] = 0;
		}
		if (!empty($user['sid'])) {
			$memberinfo['is_storeadmin'] = 1;
		} else {
			$memberinfo['is_storeadmin'] = 0;
		}

		$Agent = Agent::where(['weid' => weid(), 'uid' => $user_id])->find();
		if (!empty($Agent)) {
			$memberinfo['agent'] = $Agent->toArray();
		} else {
			$memberinfo['agent']['income'] = 0;
		}

		$Technical = Technical::where(['weid' => weid(), 'uid' => $user_id])->find();
		if (!empty($Technical)) {
			$Technical = $Technical->toArray();
		}

		if (!empty($Technical)) {
			$memberinfo['is_technical'] = $Technical['status'];
		} else {
			$memberinfo['is_technical'] = 0;
		}

		if ($memberinfo['nickname'] == '微信用户' || $memberinfo['nickname'] == '匿名用户') {
			$memberinfo['nickname'] = "";
		}

		$memberinfo['coupon'] = (int) CouponReceive::where(['weid' => weid(), 'uid' => $memberinfo['uid']])->count();

		$memberinfo['sex'] = sex($memberinfo['sex']);

		if (input('get.v') == Config::getconfig()['program_version']) {
			$memberinfo['is_audit'] = 1;
		} else {
			$memberinfo['is_audit'] = 0;
		}
        if($memberinfo['is_autonym'] == 1){
            $info = MemberAutonym::where(['uid'=>$memberinfo['id']])->find();
            if($info){
                $memberinfo['autonym_status'] = $info['status'];
            }else{
                $memberinfo['autonym_status'] = 0;
            }
        }else{
            $memberinfo['autonym_status'] = 2;
        }

		$data = $memberinfo;

		return $this->json(['data' => $data]);
	}

	public function getkefuurl()
	{
		$orderid = input('get.orderid');

		$technicalId = OrderStaff::getuuid($orderid);
		$Membermob = new Member;
		$memberinfo = $Membermob->getUserByWechat();
		$data['url'] = gethost() . TP_APIURL . '/h5-im?toid=' . Openid::getMpOpenidbyuuid($technicalId) . '&uid=' . $memberinfo['id'] . '&xmtoken=' . $this->getToken();

		return $this->json(['data' => $data]);
	}
	public function getsetmpurl()
	{
		$Membermob = new Member;
		$memberinfo = $Membermob->getUserByWechat();

		$data['url'] = gethost() . TP_APIURL . '?s=/index/member/setmpopenid&xmtoken=' . $this->getToken() . '&uid=' . $memberinfo['id'];

		return $this->json(['data' => $data]);
	}

	public function setmpopenid()
	{
		$weid = weid();
		$openid = input('get.openid');

		$backurl = gethost() . $_SERVER["SCRIPT_NAME"] . '?s=/index/member/setmpopenid&xmtoken=' . $this->getToken() . '&uid=' . input('get.uid');
		if (empty($openid)) {
			$url = gethost() . $_SERVER["SCRIPT_NAME"] . '?s=/index/wechatmp/getopenid&xmtoken=' . $this->getToken() . '&uid=' . input('get.uid') . '&backurl=' . urlencode($backurl);
			return redirect($url);
		} else {
			$uid = input('get.uid');
			if (empty(Openid::where(['weid' => $weid, 'ptype' => 'mp', 'openid' => $openid])->find())) {
				Openid::create([
					'weid' => $weid,
					'ptype' => 'mp',
					'uid' => $uid,
					'openid' => $openid
				]);
			}
		}
		echo <<< EOT
			<!DOCTYPE html>
			<html lang="zh-cmn-Hans">
			<head>
				<meta charset="UTF-8">
				<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0,viewport-fit=cover">
				<title>绑定公众号信息提醒</title>
				<link rel="stylesheet" href="static/style/weui.css"/>
			</head>
			<body ontouchstart data-weui-mode="care" >
				<div class="weui-msg">
					<div class="weui-msg__icon-area"><i class="weui-icon-success weui-icon_msg"></i></div>
					<div class="weui-msg__text-area">
						<h2 style="text-align: center;" class="weui-msg__title">设置成功</h2>
					</div>
				</div>
			</body>
			</html>
EOT;
	}

	public function openid()
	{
		$code = input('get.code');

		if ($code) {
			$app = Wxmini::make();
			$data = $app->auth->session($code);
			$data['ptype'] = 'wxapp';
			$data['sessionid'] = md5(uniqid());
		}else{
			$data = $this->userInfo;
			
		}
		$data['sessionid'] = md5(uniqid());
		$data['weid'] = weid();

		$this->setToken($data, $data['sessionid']);

		return $this->json(['data' => $data]);
	}
	public function check()
	{
		if ($this->userInfo['openid']) {
			$errno = 0;
		} else {
			$errno = 1;
		}

		return $this->json(['errno' => $errno, 'data' => $this->userInfo]);
	}
	public function userinfo()
	{
		return $this->json(['data' => $this->userInfo]);
	}

	public function getuid()
	{
		$data['uid'] = UID();
		return $this->json(['data' => $data]);
	}

	//获取用户手机号
	public function getsessionkey()
	{
		global $_GPC;

		$code = $_GPC['code'];
		$account = pdo_get('account_wxapp', array('uniacid' => weid()));
		$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $account['key'] . '&secret=' . $account['secret'] . '&js_code=' . $code . '&grant_type=authorization_code';

		$curl = new Curl();
		$curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
		$curl->get($url);
		$result = json_decode($curl->response, true);
		return $this->json(['data' => $result]);
	}

	public function updatanickname()
	{
		$postdata['nickname'] = input('post.nickName');
		$postdata['userpic'] = input('post.avatarUrl');

		if(empty($postdata['nickname'])){
			$postdata['nickname'] =  $this->userInfo['nickname'];
		}

		if(empty($postdata['userpic'])){
			$postdata['userpic'] =  $this->userInfo['avatar'];
		}

		if (!empty($postdata['nickname'])) {
			Member::where('id', UID())->update($postdata);
		}
	}

	public function bindmobile()
	{
		global $_GPC, $_W;

		$uid           = UID();
		$encryptedData = $_GPC['encryptedData'];
		$iv            = $_GPC['iv'];
		$sessionKey    = $_GPC['session_key'];
		$appid = $_W['account']['key'];

		$pc = new WxBizDataCrypt($appid, $sessionKey);
		$errCode = $pc->decryptData($encryptedData, $iv, $data);
		if ($errCode == 0) {
			$phone = json_decode($data, 'true');

			Member::update(['id' => UID(), 'telephone' => $phone['phoneNumber']]);

			return $this->json(['data' => $phone]);
		} else {
			return $this->json(['errno' => 1, 'data' => ['errcode' => $errCode, 'appid' => $appid]]);
		}
	}

	public function bindpid()
	{
		$pid = input('post.pid');

		if (empty($pid)) {
			$pid = input('get.pid');
		}

		if (!empty($pid) && !empty(UID())) {
			$Membermob = new Member;
			$memberinfo = $Membermob->getUserByWechat();

			if (empty($memberinfo['pid'])) {
				if ($memberinfo['id'] != $pid) {
					Member::where('id', UID())->update(['pid' => $pid]);
				}
			}
		}
		return $this->json(['data' => $memberinfo]);
	}

	public function team()
	{
		$data['first'] = Member::field('id,nickname,regdate,userpic')
			->where(['weid' => weid(), 'pid' => UID()])
            ->order('regdate desc')
			->select()
			->toArray();

		if (!empty($data['first'])) {
			foreach ($data['first'] as &$vo) {
				$vo['regdate'] = time_format($vo['regdate']);

				if (empty($pid)) {
					$pid = $vo['id'];
				} else {
					$pid = $pid . ',' . $vo['id'];
				}
			}
			$pidin = explode(',', $pid);

			$data['second'] = Member::field('id,nickname,regdate,userpic')
				->where(['weid' => weid(), 'pid' => $pidin])
                ->order('regdate desc')
				->select()
				->toArray();

			foreach ($data['second'] as &$vo) {
				$vo['regdate'] = time_format($vo['regdate']);
			}
		}

		return $this->json(['data' => $data]);
	}

	public function agent()
	{
		$user = Users::getuserbyuid(PUID());
		$data = Agent::field('id,uid,name,tel')
			->where(['weid' => weid(), 'uid' => $user['id']])
			->select()
			->toArray();

		return $this->json(['data' => $data]);
	}

	public function update()
	{
		$uid = UID();
		$postdata = input('post.');

		if (!empty($postdata['userpic'])) {
			$data['userpic'] = $postdata['userpic'];
		}

		if (!empty($postdata['nickname'])) {
			$data['nickname'] = $postdata['nickname'];
		}

		if (!empty($postdata['sex'])) {

			if ($postdata['sex'] == '男') {
				$data['sex'] = 1;
			} elseif ($postdata['sex'] == '女') {
				$data['sex'] = 2;
			} else {
				$data['sex'] = 0;
			}
		}
		$data['id'] = $uid;
		Member::update($data);
		return $this->json(['data' => $data]);
	}
	public function login()
	{
		$Configdata = Config::getconfig('common');
		$Membermob = new Member;
		$memberinfo = $Membermob->getUserByWechat();
		if ($Configdata['WECHAT_REGISTER_CLOSE'] == 1 && input('get.v') != Config::getconfig()['program_version']) {


			if (!empty($memberinfo['name'])) {
				if (empty($memberinfo['status'])) {
					$data['errno'] = 20001;
					return $this->json(['msg' => '账号审核中', 'data' => $data]);
				}
			} else {
				$data['errno']  = 10001;
				return $this->json(['msg' => '您没还完成注册', 'data' => $data]);
			}
		}
		$data['uid'] = $memberinfo['id'];
		$data['errno'] = 0;
		return $this->json(['data' => $data]);
	}

//	public function

    /**
     * 用户实名
     */

	public function autonym(){
        $Membermob = new Member;
        $memberinfo = $Membermob->getUserByWechat();
        if($memberinfo->is_autonym == 2){
            return $this->json(['errno'=>10001,'msg'=>'您已经实名无限重复操作']);
        }
        $data['type'] = input('post.type');
        if(!in_array($data['type'], [1,2])){
            return $this->json(['errno'=>10002,'msg'=>'类型错误']);
        }

        $data['name'] = input('post.name');
        if(empty($data['name'])){
            return $this->json(['errno'=>10002,'msg'=>'请填写姓名']);
        }
        $data['id_number'] = input('post.id_number');
        if(empty($data['id_number'])){
            return $this->json(['errno'=>10002,'msg'=>'请填写身份号']);
        }
        if(!validateIDCard($data['id_number'])){
            return $this->json(['errno'=>10002,'msg'=>'身份证号格式不对']);
        }
        $data['mobile'] = input('post.mobile');
        if(empty($data['mobile'])){
            return $this->json(['errno'=>10002,'msg'=>'请填写手机号']);
        }
        if(!validatePhoneNumber($data['mobile'])){
            return $this->json(['errno'=>10002,'msg'=>'手机号格式错误']);
        }
        $data['province'] = input('post.province');
        if(empty($data['province'])){
            return $this->json(['errno'=>10002,'msg'=>'缺少省']);
        }

        $data['city'] = input('post.city');
        if(empty($data['city'])){
            return $this->json(['errno'=>10002,'msg'=>'缺少市']);
        }
        $area = input('post.area');
        if($area){
            $data['area'] = $area;
        }

        $data['image_a'] = input('post.image_a');
        if(empty($data['image_a'])){
            return $this->json(['errno'=>10002,'msg'=>'缺少身份证正面']);
        }

        $data['image_b'] = input('post.image_b');
        if(empty($data['image_b'])){
            return $this->json(['errno'=>10002,'msg'=>'缺少身份证反面']);
        }

        if($data['type']==2){
            $data['image_c'] = input('post.image_c');
            if(empty($data['image_c'])){
                return $this->json(['errno'=>10002,'msg'=>'营业执照必填']);
            }

        }

        $operatingcityInfo = Operatingcity::where(['city_name'=>$data['city']])->find();
        if($operatingcityInfo){
            $where = [];
            if($operatingcityInfo['areatype'] == 0 && $area){
                $operatingcityInfo = Operatingcity::where(['district_name'=>$area])->find();
                if($operatingcityInfo){
                    $where['uuid'] = $operatingcityInfo['uuid'];
                }
            }else{
                $where['uuid'] = $operatingcityInfo['uuid'];
            }
            if($where){
                $data['user_id'] = Users::where(['uuid'=>$operatingcityInfo['uuid']])->value('id');
            }
        }
        $ids =  input('post.ids');
        if($ids){
            $info = MemberAutonym::where(['id'=>$ids])->find();
            if(!$info){
                return $this->json(['msg' => '数据不存在',['errno'=>10001]]);
            }
            if($info['status'] != 3){
                return $this->json(['msg' => '数据审核中不能编辑',['errno'=>10001]]);
            }
            $data['status']      = 1;
            $data['id']          = $ids;
            $data['update_time'] = time();
            MemberAutonym::update($data);
        }else{
            $info = MemberAutonym::where(['uid'=>UID(),'weid'=>weid()])->find();
            if($info){
                return $this->json(['msg' => '数据正在审核中',['errno'=>10001]]);
            }
            $data['uid']         = UID();
            $data['weid']        = weid();
            $data['create_time'] = time();
            MemberAutonym::create($data);
        }
        return $this->json(['msg' => '申请成功']);
    }

    /**
     * 审核详情
     */

    public function autonym_info(){
        $info = MemberAutonym::where(['uid'=>UID(),'weid'=>weid()])->find();
        return $this->json(['info' => $info]);
    }

	/**
     * 发布转让
     */

	public function transfer(){
        $Membermob = new Member;
        $memberinfo = $Membermob->getUserByWechat();
        if($memberinfo['is_autonym'] != 2){
            return $this->json(['errno'=>10001,'msg'=>'请先完成认证']);
        }
        $data['publish_type']   = input('post.publish_type');//转让
        $data['name']        = input('post.name');
        $data['is_spec']     = input('post.is_spec');
        $data['price']       = input('post.price');
        $data['found_time']  = input('post.found_time');
        $data['capital']     = input('post.capital');
        $data['type']        = input('post.type');
        $data['profession']  = input('post.profession');
        $data['ratepaying']  = input('post.ratepaying');
        $data['bank']        = input('post.bank');
        $data['buy_demand']      = input('post.demand');
        $data['mobile']   = input('post.mobile');
        $data['invoice']     = input('post.invoice');
        $data['uid']         = UID();
        $data['weid']        = weid();
        $data['address']     = input('post.address');
        $data['province_name'] = input('post.province_name');
        $data['city_name']     = input('post.city_name');
        $data['district_name'] = input('post.district_name');
        $data['miaoshu']       = input('post.miaoshu');
//        if(empty($data['name']) || empty($data['found_time']) || empty($data['capital']) || empty($data['type']) || empty($data['profession']) || empty($data['ratepaying']) || empty($data['bank']) || empty($data['chinabank']) || empty($data['invoice'])){
//            return $this->json(['msg' => '缺少参数',['errno'=>10001]]);
//        }
        if(empty(input('post.id'))){
            $data['create_time'] = time();
            MemberTransfer::create($data);
            $msg = '发布成功';
        }else{
            $data['id'] = input('post.id');
            $info = MemberTransfer::where(['id'=>$data['id']])->find();
            if(!$info){
                return $this->json(['errno'=>10001,'msg'=>'数据不存在']);
            }
            $data['status'] = 0;
            MemberTransfer::update($data);
            $msg = '编辑成功';
        }

        return $this->json(['msg' => $msg]);
    }

    /**
     * 列表
     */

    public function transfer_list(){
        $is_user       = input('is_user');
        $query         = new MemberTransfer();
        if($is_user){
            $query = $query->where(['uid'=>UID()]);
        }else{
            $query = $query->where(['status'=>1]);
        }
        $query    =  $query->where(['weid' => weid()]);
        $type          = input('get.publish_type');
        if($type){
            $query = $query->where(['publish_type'=>$type]);
        }
        $status          = input('get.status');
        if(isset($status)){
            $query = $query->where(['status'=>$status]);
        }
        $key           = input('get.key');
        if($key){
            $query = $query->where('name|buy_demand','like','%'.$key.'%');
        }
        $province_name = input('get.province_name');
        $city_name     = input('get.city_name');
        $district_name = input('get.district_name');
        if($province_name){
            $query  = $query->where(['province_name'=>$province_name]);
        }
        if($city_name){
            if(!$is_user){
                $query  = $query->where(['city_name'=>$city_name]);
            }

        }else{
//            return $this->json(['data' => []]);
        }
        if($district_name && !$is_user){
            $query  = $query->where(['district_name'=>$district_name]);
        }
        $start_time = input('get.start_time');
        $end_time   = input('get.end_time');
        if($start_time && $end_time){
//            $query  = $query->whereTime('create_time','between',[strtotime($start_time) ,strtotime($end_time)]);
            $query  = $query->whereBetween('found_time',[$start_time ,$end_time]);
        }
        $ratepaying = input('ratepaying');
        if($ratepaying){
            $query  = $query->where(['ratepaying'=>$ratepaying]);
        }
        $capital_min = input('capital_min');
        $capital_max = input('capital_max');
        if($capital_min && $capital_max){
            $query = $query->whereBetween('capital', [$capital_min, $capital_max]);
        }
        $bank = input('bank','');
        if($bank){
            $query  = $query->where(['bank'=>$bank]);
        }
        $type = input('type','');
        if($type){
            $query  = $query->where(['type'=>$type]);
        }
        $profession = input('profession');
        if($profession){
            $query = $query->where('profession','like','%'.$profession.'%');
        }
        $data = $query->order('id desc')->paginate();
        return $this->json(['data' => $data]);
    }

    public function transfer_info(){
        $where['id']    = input('post.ids');
//        $where['status'] = 1;
        if(empty($where['id'])){
            return $this->json(['msg' => '数据不存在',['errno'=>10001]]);
        }
        $data = MemberTransfer::where($where)->find();
        return $this->json(['data' => $data]);
    }

    /**
     * 求购
     */

    public function buy(){
        $Membermob = new Member;
        $memberinfo = $Membermob->getUserByWechat();
        if($memberinfo->is_autonym != 2){
//            return $this->json(['errno'=>10001,'msg'=>'请先完成认证']);
        }
        $data['buy_demand']      = input('post.demand');
        $data['is_spec']         = input('post.is_spec');
        $data['price']           = input('post.price');
        $data['ratepaying']      = input('post.ratepaying');
        $data['bank']            = input('post.bank');
        $data['invoice']         = input('post.invoice');
        $data['uid']             = UID();
        $data['weid']            = weid();
        $data['publish_type']    = 2;//2求购
        if(empty($data['buy_demand'])){
            return $this->json(['msg' => '缺少参数',['errno'=>10001]]);
        }
        $data['create_time'] = time();
        MemberTransfer::create($data);
        return $this->json(['msg' => '发布成功']);
    }


    /**
     * 删除
     */

    public function del_transfer(){
        $ids = input('ids');
        if(!$ids){
            return $this->json(['errno'=>10001,'msg'=>'缺少参数']);
        }
        $res = MemberTransfer::where(['id'=>$ids,'weid'=>weid()])->delete();
        if(!$res){
            return $this->json(['msg' => '删除失败']);
        }
        return $this->json(['msg' => '删除成功']);
    }

}
